/**
 * 输入文本域操作
 * author
 * 输入文本框相关操作包括
 */
fangimjs.define('view/textareaView', ['jquery', 'event/event', 'setting/setting'], function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        setting = require('setting/setting').getInstance(),
        event = require('event/event');

    function textareaView() {
        // 新增属性，确定用户是否可以输入。
        this.status = 'active';
        this.chatWPic = '#chatW_l_pic';//上传图片按钮容器id
        this.chatWTA = '#chatW_l_text';//输入框id
        this.chatWFace = '#chatW_l_face';
        this.chatFaceBtn = '#chatW_l_btn_face';
        this.chatSendBtn = '#chatW_l_btn_send';//发送按钮id
        this.chatWHis = '#chatW_l_his';//历史按钮
        this.defaultText = '点击这里，直接输入消息咨询...';//默认提示语，\u70b9\u51fb\u8fd9\u91cc\uff0c\u76f4\u63a5\u8f93\u5165\u6d88\u606f\u54a8\u8be2\u002e\u002e\u002e
    };
    textareaView.prototype = {
        /**
         * 初始化函数
         */
        init: function () {
            var that = this;
            that.textarea = $(that.chatWTA);
            that.sendButton = $(that.chatSendBtn);
            that.textarea.on('focus', function (e) {
                var $this = $(this);
                if(that.picData) {
                    $this.blur();
                } else {
                    var msg = $this.val();
                    $this.css('color', '#000');
                    if(msg && msg == that.defaultText) {
                        $this.val('');
                    }
                }
            });
            that.textarea.on('blur', function (e) {
                var $this = $(this),
                    msg = $this.val();
                if (!msg && !that.picData) {
                    $this.css('color', '').val(that.defaultText);
                }
            });

            that.textarea.on("keydown", function (e) {
                // 2.0.6 改为回车发送
                if (e.keyCode === 13) {
                    e.preventDefault();
                    that.showImg(that.picData);
                    that.sendMsg();
                }
            });
            that.jChatWHis = $(that.chatWHis).on("click", function () {
                event.trigger("view:msg:history");
            });
            that.sendButton.on("click", function () {
                that.sendMsg();
            });
            // 表情
            that.faceBtn = $(that.chatFaceBtn);
            that.faceBox = $(that.chatWFace);
            that.faceBoxInner = that.faceBox.find('.bqcon').on('click', 'img', function(event) {
                event.stopPropagation();
                that.toggleFaceBox();
                if(that.textarea.val() === that.defaultText) {
                    that.textarea.val('');
                }
                that.textarea.focus();
                that.insertFace('[' + $(this).attr('data-face') + ']');
            });
            that.faceBtn.on('click', function(event) {
                event.stopPropagation();
                if (!that.faceBoxInner.html()) {
                    that.faceBoxInner.html(that.createFaceBox());
                }
                that.toggleFaceBox();
            });
            $(document).click(function(){
                that.faceBtn.removeClass('on');
                that.faceBox.hide();
            });
            //图片上传
            that.picForm = $(that.chatWPic);
            that.file = that.createFileInput();
            //上传图片限制类型
            that.fileType = ["jpeg", "jpg", "gif", "png", "bmp"];
            //图片上传完成时的回调
            var win = window;
            win.FangChat = win.FangChat || {};
            //图片上传回调函数
            win.FangChat.picUploadComplete = function (data) {
                that.closeTip();
                if (!data) {
                    that.showTip('上传图片错误，请稍后上传', true);// \u4e0a\u4f20\u56fe\u7247\u51fa\u9519\uff01\u8bf7\u91cd\u65b0\u4e0a\u4f20\u3002
                } else {
                    that.picData = data;
                    event.trigger('view:image:upload', data);
                    that.showTip('图片上传成功，请发送。 <a href="' + data + '" target="_blank" data-id="look">\u67e5\u770b</a> <a href="javascript:;" data-id="del">\u5220\u9664</a>');// \u56fe\u7247\u4e0a\u4f20\u6210\u529f\uff0c\u8bf7\u53d1\u9001\u3002
                }
                that.file = that.createFileInput();
            };
        },
        /**
         * 发送消息
         */
        sendMsg: function () {
            var that = this;
            that.closeTip();
            //优先发送图片
            //var msg = that.picData || $.trim(that.textarea.val()).replace(/[\<\>\(\)\{\}\[\]"',;!]/g,'');
            var msg = that.picData || $.trim(that.textarea.val());
            // if(!msg) {
            //     msg = $.trim(that.textarea.val());
            //     msg = msg.replace(/\</g, '&lt;');
            //     msg = msg.replace(/\>/g, '&gt;');
            //     msg = msg.replace(/\"/g, '&quot;');
            //     msg = msg.replace(/\s+/g, '&nbsp;');
            //     msg = msg.replace(/\n/g, '<br/>');
            // }
            if (msg == this.defaultText || msg == '') {
                that.showTip('发送内容不能为空，请重新输入...', true);//\u53d1\u9001\u5185\u5bb9\u4e0d\u80fd\u4e3a\u7a7a\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165\u3002
                that.textarea.focus();
                return false;
            }
            that.clearTextarea();
            that.picData = undefined;
            event.trigger('view:msg:send', msg);
        },
        /**
         * 上传图片
         */
        uploadTalkPic: function () {
            var that = this;
            var city = fangimjs.data.vars.config.city;
            var backurl = setting.UPLOAD_IMG_BACK_URL_PATH;
            /*(function (window) {
             var url = window.location.href;
             var index = url.lastIndexOf('/');
             return url.substring(0, index) + '/imguploaded.html';
             })(window);*/
            var sid = Math.round(Math.random() * 100);
            var uploadUrl = setting.UPLOAD_IMG_PATH+'&sid=' + sid + '&backurl=' + backurl;
            //加简单的图片验证
            if (that.checkFileType()) {
                var name = that.createLoadFrame();
                that.picForm.attr({
                    'action': uploadUrl,
                    'encoding': "multipart/form-data",
                    'target': name,
                    'method': "Post"
                });
                that.showTip('上传中，请稍候...');//\u4e0a\u4f20\u4e2d\uff0c\u8bf7\u7a0d\u5019\u002e\u002e\u002e
                that.picForm.submit();
            }
        },
        /**
         * 创建发送图片input按钮
         * @returns {*}
         */
        createFileInput: function () {
            var that = this;
            var sid = Math.round(Math.random() * 10000);
            var name = 'img' + sid;
            if (that.file) {
                that.file.off().remove();
            }
            if (window.location.host.indexOf('fang.com') === -1) {
                //如果主域名不是'fang.com',不支持图片上传
                return false;
            }
            var html = '<input name="file' + sid + '" type="file" title="\u53d1\u9001\u56fe\u7247" style="filter:alpha(opacity=0);opacity:0;cursor:pointer;display:block;margin-left:-70px;margin-top:-5px;">';//text-indent: -999px;发送图片
            that.file = $(html);
            that.picForm.empty().append(that.file);
            that.file.on('change', function (e) {
                that.uploadTalkPic();
            });
            return that.file;
        },
        /**
         * 创建图片加载iframe（跨域处理）
         * @returns {string}
         */
        createLoadFrame: function () {
            var that = this;
            var name = 'fc' + that.file.attr('name');
            var oldname = fangimjs.data.vars.picframe;
            $('iframe[name=' + oldname + ']').remove();
            fangimjs.data.vars.picframe = name;
            $('<iframe name="' + name + '" width="0" height="0" scrolling="no" frameBorder="0" style="visibility:hidden;"></iframe>').appendTo(document.body);
            return name;
        },
        /**
         * 检查图片文件类型
         * @returns {boolean}
         */
        checkFileType: function () {
            var that = this;
            var filename = that.file.val();
            var ret = false;
            var index = filename.lastIndexOf(".");
            if (index != -1) {
                var fileType = (filename.substr(index + 1)).toLowerCase();
                if ($.inArray(fileType, that.fileType) === -1) {
                    alert("\u4e0d\u652f\u6301\u6587\u4ef6\u7c7b\u578b" + fileType + ",\u652f\u6301" + that.fileType.join(',') + "\u56fe\u7247\u7c7b\u578b\u6587\u4ef6\uff01");//不支持文件类型，支持，图片类型文件！
                } else {
                    ret = true;
                }
            } else {
                alert("\u8bf7\u4e0a\u4f20" + that.fileType.join(',') + "\u56fe\u7247\u7c7b\u578b\u6587\u4ef6\uff01");//请上传,图片类型文件！
            }
            return ret;
        },
        createFaceBox: function() {
            var that = this;
            var faceimg = '', emojis = fangimjs.data.vars.emojis;
            // 通过循环创建60个表情，可扩展
            for (var key in emojis) {
                faceimg += '<a href="javascript:void(0)"><img src="' + fangimjs.data.base + 'images/emoji_s/' + emojis[key] + '" width="24" data-face="' + key + '" title="' + key + '"/></a>';
            }
            return faceimg;
        },
        toggleFaceBox: function() {
            var that = this;
            if(that.faceBtn.hasClass('on')) {
                that.faceBtn.removeClass('on');
                that.faceBox.hide();
            } else {
                that.faceBtn.addClass('on');
                that.faceBox.show();
            }
        },
        // 光标插入和选择替换插入
        insertFace: function(myValue, t) {
            var that = this;
            var wta = document.getElementById(that.chatWTA);
            var $t = that.textarea[0];
            // 如果是旧版本IE
            if (document.selection) {
                $t.focus();
                var sel = document.selection.createRange();
                sel.text = myValue;
                $t.focus();
                var l = $t.value.length;
                sel.moveStart('character', -l);
                var wee = sel.text.length;
                if (arguments.length == 2) {
                    sel.moveEnd('character', wee + t);
                    if (t <= 0) {
                        sel.moveStart('character', wee - 2 * t - myValue.length);
                    } else {
                        sel.moveStart('character', wee - t - myValue.length);
                    }
                    sel.select();
                }
            } else if ($t.selectionStart || $t.selectionStart == '0') {
                var startPos = $t.selectionStart;
                var endPos = $t.selectionEnd;
                var scrollTop = $t.scrollTop;
                $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                $t.focus();
                $t.selectionStart = startPos + myValue.length;
                $t.selectionEnd = startPos + myValue.length;
                $t.scrollTop = scrollTop;
                if (arguments.length == 2) {
                    $t.setSelectionRange(startPos - t, $t.selectionEnd + t);
                    $t.focus();
                }
            } else {
                $t.value += myValue;
                $t.focus();
            }
        },
        /**
         * 输入相关提示
         *
         * 发送内容不能为空，请重新输入。
         * 上传失败，请重试。
         * 上传中，请稍候...
         * @returns {boolean}
         */
        showTip: function (text, autoClose) {
            var that = this;
            if (!that.tip) {
                that.tip = $('<p class="talkNull gray6" style="display: none"></p>');
                that.textarea.before(that.tip);
                that.tip.on('click', 'a[data-id=del]', function () {
                    event.trigger('view:image:del');
                    that.closeTip();
                });
            }
            that.tip.html(text).show();
            that.clearTextarea();
            if (autoClose) {
                that.tip.removeClass('iconChenggong');
                setTimeout(function () {
                    that.closeTip();
                }, 3000);
            } else {
                that.tip.addClass('iconChenggong');
            }
        },
        /**
         * 关闭提示
         */
        closeTip: function () {
            var that = this;
            if (that.tip) {
                that.tip.hide();
            }
        },
        /**
         * 显示图片
         * @param data
         */
        showImg: function (data) {
            var that = this;
            that.picData = data;
            that.closeTip();
            if (data) {
                that.showTip('你上传过图片，请发送。 <a href="' + data + '" target="_blank" data-id="look">\u67e5\u770b</a> <a href="javascript:;" data-id="del">\u5220\u9664</a>');//\u4f60\u4e0a\u4f20\u8fc7\u56fe\u7247\uff0c\u8bf7\u53d1\u9001\u3002
                that.clearTextarea();
            } else {
                //that.textarea.val(that.defaultText);
                that.textarea.focus();
            }
        },
        clearTextarea: function() {
            this.textarea.val('');
        },
        updateUI: function (history) {
            var that = this;
            var width = history?1:0;
            that.jChatWHis.css("border", width+"px solid #999");
        },
        lockTextarea: function() {
            this.status = 'locked';
            this.textarea.css('color', '#fff').attr('disabled', true);
            this.sendButton.css('background-color', '#888').off('click');
            this.faceBtn.off('click');
            this.file.attr('disabled', true);
        }
    };
    module.exports = new textareaView;
});
